# -*- coding:utf-8 -*-
from manager.models import *
from userprofile.models import *
from .ext import common as common_tools
from .ext.excelhelper import render_to_excel
from django.contrib.auth.models import User, Group
from django.contrib import auth
from django.db.models import Sum, Count
from django.db import connection
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, render_to_response, HttpResponseRedirect, HttpResponse
from multiprocessing.connection import Client  # 给通道 用的，发socket给PPS
import json, datetime, requests, time


@csrf_exempt
def coil(request):  # 继电器模块地感信号
    coil_msg = request.POST.get('coil_events')
    print('收到输入信号：', coil_msg)
    if '+OCCH_ALL' not in coil_msg:
        return HttpResponse('input error')

    msg_cut = coil_msg.split(':')
    count_msg = list(msg_cut[1].split(','))
    num = 1
    for channel in count_msg:
        if channel == '1':
            params = {'channel': num, }
            url = 'http://127.0.0.1:5000/events'  # 客户端的IP
            print(params, url)
            r = requests.post(url, params)
            print(r.text)
        num = num + 1
    return HttpResponse('OK')


@csrf_exempt
def coil_command(request):  # 控制道闸
    coil = request.POST.get('coil_cmd')
    coil_cmd = coil + '=1,200\n'
    print('继电器命令:', coil_cmd)
    try:
        c = Client(('localhost', 25000), authkey=b'sherry')
        c.send(coil_cmd)
        print("Hi,pipe send:", c.recv())  # 如果不打印c.recv(),BaseTcpClient.py服务会显示主动断开连接
        c.close()
    except:
        print('socket有误')
        pass
    return HttpResponse('cmd_ok')


@csrf_exempt
def in_parking_list(request):
    msg = request.POST.get('msg')
    mymsg = json.loads(msg)
    print(mymsg)
    picresult = mymsg.get('result')
    now_save = mymsg.get('save')
    pictime = mymsg.get('time')
    picname = mymsg.get('picname')
    car_type = mymsg.get('car_type')

    if now_save == True:  # 放行存数据库
        # 存进库消息
        print(car_type,type(car_type))
        filename = '/home/tlpark/upark/upload/' + picname
        inpark_obj = EventLog.objects.create()
        inpark_obj.card_num = picresult
        inpark_obj.in_timer = pictime
        inpark_obj.in_pic = filename
        inpark_obj.car_type = car_type
        inpark_obj.save()
    else:  # 查找车类型的
        if car_type != 2:

            user_obj = UserPaymentLog.objects.filter(user__car_number__iexact=picresult, end_time__gte=pictime)
            if user_obj:
                car_type = 0
            else:
                car_type = 1

    return HttpResponse(car_type)


@csrf_exempt
def out_parking_list(request):
    msg = request.POST.get('msg')
    mymsg = json.loads(msg)
    print(mymsg)
    picresult = mymsg.get('result')
    pictime = mymsg.get('time')
    picname = mymsg.get('picname')
    filename = '/home/tlpark/upark/upload/' + picname
    # print(type(picresult) , picresult)
    if picresult == '无法进库记录匹配':
        obj = EventLog.objects.create()
        # 存出库消息
        obj.card_num = '无匹配'
        obj.out_timer = pictime
        obj.car_type = 1
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        obj.save()
        myid = obj.id
        return JsonResponse({'car_type': 11, 'myid': myid})  # 没有找到匹配的进入信息
    if picresult == '':
        return JsonResponse({'car_type': 11})  # 没有找到匹配的进入信息

    obj = EventLog.objects.filter(card_num=picresult, counteract=0).order_by('in_timer').first()
    if obj:
        car_type = obj.car_type
        in_time = str(obj.in_timer)
        in_pic = obj.in_pic
        myid = obj.id
        # 存出库消息
        obj.out_timer = pictime
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        obj.save()
    else:
        user_obj = UserPaymentLog.objects.filter(user__car_number__iexact=picresult, end_time__gte=pictime)
        if user_obj:
            car_type = 0
            obj = EventLog.objects.create()
            # 存出库消息
            obj.card_num = '无匹配'
            obj.car_type = 0
            obj.out_timer = pictime
            obj.out_pic = filename
            obj.counteract = 1  # 出入抵消了
            obj.save()
            myid = obj.id
            return JsonResponse({'car_type': car_type, 'inpark_time': pictime, 'myid': myid})
        else:
            return JsonResponse({'car_type': 11})  # 没有找到匹配的进入信息

    # 返回入库信息
    return JsonResponse({'car_type': car_type, 'inpark_time': in_time, 'in_pic': in_pic, 'myid': myid})


@csrf_exempt
def result_error_list(request):
    # 所有没抓到的车牌，或者识别抓错了的车牌都放在这里了。
    maybe_num = request.POST.get('car_num')
    find_type = int(request.POST.get('find_type'))
    data_list = []
    print(find_type, type(find_type))
    if find_type == 1:
        obj1 = EventLog.objects.filter(card_num__contains=maybe_num, counteract=0)
    elif find_type == 2:
        obj1 = EventLog.objects.filter(card_num='', counteract=0)
    else:
        obj1 = EventLog.objects.filter(counteract=0).order_by('Card_num')
    print(obj1)
    for item in obj1:
        pic_msg = {}
        pic_msg['pic'] = item.in_pic
        pic_msg['id'] = str(item.id)
        data_list.append(pic_msg)
    print(data_list)
    return HttpResponse(json.dumps(data_list))


@csrf_exempt
def makit(request):
    msg = request.POST.get('msg')
    mymsg = json.loads(msg)
    print(mymsg)
    picresult = mymsg.get('result')
    pictime = mymsg.get('time')
    picname = mymsg.get('picname')
    myid = mymsg.get('id')
    filename = '/home/tlpark/upark/upload/' + picname
    # print(type(picresult) , picresult)

    obj = EventLog.objects.get(id=int(myid))
    if obj:
        myid = obj.id
        in_time = str(obj.in_timer)
        car_type = obj.car_type
        obj.card_num = picresult
        # 存出库消息
        obj.out_timer = pictime
        obj.out_pic = filename
        obj.counteract = 1  # 出入抵消了
        obj.save()
    else:
        return JsonResponse({'car_type': 11})  # 没有找到匹配的进入信息

    # 返回入库信息
    return JsonResponse({'car_type': car_type, 'inpark_time': in_time, 'myid': myid})


@csrf_exempt
def payment_spot(request):
    msg = request.POST.get('msg')
    mymsg = json.loads(msg)
    print(mymsg)
    myid = mymsg.get('myid')
    payable = mymsg.get('payable')
    actuallypay = mymsg.get('actuallypay')
    if myid < 0:
        obj = EventLog.objects.create()
        obj.actuallypay = actuallypay
        obj.payable = payable
        obj.save()
        return HttpResponse('payment ok')

    obj = EventLog.objects.get(id=myid)
    if obj:
        obj.actuallypay = actuallypay
        obj.payable = payable
        obj.save()
    return HttpResponse('payment ok')


@csrf_exempt
def events(request):
    """
    事件列表
    :param request:
    :return:
    """
    context = {}
    now = datetime.datetime.now()
    start = now - datetime.timedelta(hours=47, minutes=59, seconds=59)
    events_list = EventLog.objects.filter(In_lot__Timer__gt=start)
    print(events_list)

    context['events_list'] = events_list
    return render(request, 'manager/events_list.html', context)


@csrf_exempt
def Parking_msg(request):  # 取得停车场信息
    msg = ParkingLot.objects.filter(id=1)
    if msg:
        msg = ParkingLot.objects.get(id=1)
    else:
        return JsonResponse({'name': None})
    row = {}
    row['name'] = msg.Parking_name
    row['total'] = msg.Total_num
    row['interim'] = msg.Interim_num
    row['timer_st'] = msg.Work_time_st
    row['timer_ed'] = msg.Work_time_ed
    row['user'] = msg.Admin.username

    return HttpResponse(json.dumps(row))


@csrf_exempt
def Parking_config(request):  # 修改或新增厂库信息
    in_name = request.Post.get('name')
    in_total = request.Post.get('total')
    in_interim = request.POST.get('interim')
    in_timer_st = request.POST.get('timer_st')
    in_timer_ed = request.POST.get('timer_ed')
    in_user = request.POST.get('user')

    user_obj = User.objects.filter(username=in_user)
    if user_obj:
        user_obj = User.objects.get(username=in_user)
        admin = user_obj.username
    else:
        admin = None

    msg = ParkingLot.objects.filter(id=1)
    if msg:
        msg = ParkingLot.objects.get(id=1)
    else:
        msg = ParkingLot.objects.create()
    msg.Work_time_ed = in_timer_ed
    msg.Work_time_st = in_timer_st
    msg.Interim_num = in_interim
    msg.Total_num = in_total
    msg.Parking_name = in_name
    msg.Admin = admin
    msg.save()

    return HttpResponse('success')


@csrf_exempt
def index(request):
    """
    管理端首页
    :param request:
    :return:
    """
    context = {}
    return render(request, 'index.html', context=context)


@csrf_exempt
def page_not_found(request):
    context = {}
    return render(request, 'error404.html', context=context)


def login(request):
    """
    登录
    :param request:
    :return:
    """
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('pwd')
        user = auth.authenticate(username=username, password=password)
        if user:
            auth.login(request, user)
            go_to = '/'
            next = request.GET.get('next', None)
            if next:
                go_to = next
            return HttpResponseRedirect(go_to)
        else:
            return render(request, 'login.html',
                          {'error': "用户名或密码输入错误.", 'username': username, 'pwd': password})
    else:
        return render(request, 'login.html')


def logout(request):
    """
    logout
    :param request:
    :param arg:
    :return:
    """
    auth.logout(request)
    return HttpResponseRedirect('/login')


@login_required()
# @common_tools.permission_required
def report(request, id):
    """
    报表
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    print(start_time, end_time, '======')
    if not start_time:
        start_time = (datetime.datetime.now() - datetime.timedelta(days=7)).strftime('%Y-%m-%d')
    if not end_time:
        end_time = datetime.datetime.now().strftime('%Y-%m-%d')
    context['start_time'] = start_time
    context['end_time'] = end_time
    if id == '1':
        return render(request, 'manager/report_income.html', context)
    else:
        return render(request, 'manager/report_flow.html', context)


@login_required()
def report_income(request):
    """
    车场收入
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    if not start_time:
        start_time = datetime.datetime.now() - datetime.timedelta(days=7)
    if not end_time:
        end_time = datetime.datetime.now()
    date = datetime.datetime.now()
    start_time = datetime.datetime.strptime('%s %s:%s:%s' % (start_time, date.hour, date.minute, date.second),
                                            '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime('%s %s:%s:%s' % (end_time, date.hour, date.minute, date.second),
                                          '%Y-%m-%d %H:%M:%S')
    day_list = common_tools.get_days(start_time, end_time)
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time, counteract=1) \
        .extra(select=select) \
        .values('day').annotate(income=Sum('actuallypay')) \
        .order_by('day')
    income_dict = {}
    parking_list = []
    series_list = []
    for event in event_logs:
        print(event)
        income_dict[event['day']] = event['income']
    tmp = {
        'name': '车场收入',
        'type': 'line',
        'data': []
    }
    for day in day_list:
        tmp['data'].append(income_dict.get(day, 0) or 0)
    series_list.append(tmp)
    context['day_list'] = day_list
    context['series_list'] = series_list
    context['parking_list'] = parking_list
    return HttpResponse(json.dumps(context))


@login_required()
def report_flow(request):
    """
    车场流量
    :param request:
    :return:
    """
    context = {}
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    print(start_time, end_time, '----------')
    if not start_time:
        start_time = datetime.datetime.now() - datetime.timedelta(days=7)
    if not end_time:
        end_time = datetime.datetime.now()
    date = datetime.datetime.now()
    start_time = datetime.datetime.strptime('%s %s:%s:%s' % (start_time, date.hour, date.minute, date.second),
                                            '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime('%s %s:%s:%s' % (end_time, date.hour, date.minute, date.second),
                                          '%Y-%m-%d %H:%M:%S')
    day_list = common_tools.get_days(start_time, end_time)
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time) \
        .extra(select=select) \
        .values('day').annotate(flow=Count('id')) \
        .order_by('day')
    flow_dict = {}
    parking_list = []
    series_list = []
    for event in event_logs:
        flow_dict[event['day']] = event['flow']
    tmp = {
        'name': '车场进出流量',
        'type': 'line',
        'data': []
    }
    for day in day_list:
        tmp['data'].append(flow_dict.get(day, 0) or 0)
    series_list.append(tmp)
    context['day_list'] = day_list
    context['series_list'] = series_list
    context['parking_list'] = parking_list
    return HttpResponse(json.dumps(context))


@login_required()
def export_flow(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time) \
        .extra(select=select) \
        .values('day').annotate(flow=Count('id')) \
        .order_by('day')
    export_data = []
    for row in event_logs:
        export_data.append([row['day'], row['flow']])
        print('--->>', row)
    return render_to_excel(['日期', '流量'], export_data, 'flow.xls', title='车场流量一览')


@login_required()
def export_income(request):
    start_time = request.GET.get('start_time')
    end_time = request.GET.get('end_time')
    select = {'day': connection.ops.date_trunc_sql('day', 'update_at')}
    event_logs = EventLog.objects \
        .filter(update_at__gte=start_time, update_at__lt=end_time, counteract=1) \
        .extra(select=select) \
        .values('day').annotate(income=Sum('actuallypay')) \
        .order_by('day')
    export_data = []
    for row in event_logs:
        export_data.append([row['day'], row['income']])
    return render_to_excel(['日期', '收入'], export_data, 'income.xls', title='车场收入一览')


@csrf_exempt
def events(request):
    """
    事件列表
    :param request:
    :return:
    """
    context = {}
    now = datetime.datetime.now()
    start = now - datetime.timedelta(hours=47, minutes=59, seconds=59)
    events_list = EventLog.objects.filter(in_timer__gt=start)
    context['events_list'] = events_list
    return render(request, 'manager/events_list.html', context)
